package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.listener.easyexcel.SysAmazonListener;
import com.settlement.system.model.entity.SysAmazon;
import com.settlement.system.model.form.SysAmazonForm;
import com.settlement.system.model.query.SysAmazonQuery;
import com.settlement.system.model.vo.SysAmazonImportVo;
import com.settlement.system.service.SysAmazonService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 亚马逊账号表 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-07-23
 */
@RestController
@RequestMapping("/api/v1/amazon")
@RequiredArgsConstructor
public class SysAmazonController {

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;

    private final SysAmazonService sysAmazonService;

    @Operation(summary = "亚马逊账号表分页", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/page")
    public PageResult<SysAmazon> getPage(@ParameterObject SysAmazonQuery queryParams) {
        Page<SysAmazon> result = sysAmazonService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存亚马逊账号表", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:amazon:save')")
    public Result<?> saveSysAmazon(@RequestBody @Valid SysAmazonForm sysAmazonForm) {
        boolean result = sysAmazonService.saveSysAmazon(sysAmazonForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取亚马逊账号表信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<SysAmazonForm> getSysAmazonFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        SysAmazonForm sysAmazon = sysAmazonService.getSysAmazonFormData(id);
        return Result.success(sysAmazon);
    }

    @Operation(summary = "删除亚马逊账号表", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:amazon:delete')")
    public Result<?> deleteSysAmazon(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysAmazonService.deleteSysAmazon(ids);
        return Result.judge(result);
    }

    @Operation(summary = "注册亚马逊账号", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/register/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:amazon:register')")
    public Result<?> register(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = sysAmazonService.register(ids);
        return Result.judge(result);
    }

    @Operation(summary = "更新亚马逊账号")
    @PostMapping("/updateStatus")
    public Result<?> updateStatus(@RequestBody @Valid List<SysAmazonForm> sysAmazonFormList) {
        boolean result = sysAmazonService.updateStatus(sysAmazonFormList);
        for (SysAmazonForm sysAmazonForm : sysAmazonFormList) {
            AmazonContext.REGISTER_AMAZON_QUEUE.removeIf(item -> Objects.equals(item.getEmail(), sysAmazonForm.getEmail()));
        }
        return Result.judge(result);
    }

    @Operation(summary = "获取50条未注册的亚马逊进行注册")
    @GetMapping("/getAmazonMissions")
    public Result<?> getAmazonMissions(HttpServletRequest request) {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        List<SysAmazon> unRegisterAmazonList = sysAmazonService.getAmazonMissions();
        return Result.success(unRegisterAmazonList);
    }

    @Operation(summary = "亚马逊账号表导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/sysAmazonImport")
    @PreAuthorize("@ss.hasPerm('sys:amazon:import')")
    @PreventDuplicateSubmit
    public Result<?> sysAmazonImport(@RequestParam("file") MultipartFile file) throws Exception {
        SysAmazonListener listener = new SysAmazonListener();
        EasyExcelFactory.read(file.getInputStream(), SysAmazonImportVo.class, listener).sheet(0).doRead();
        List<SysAmazonImportVo> list = listener.getVos();
        if (list == null || list.size() == 0) {
            return Result.success();
        }
        sysAmazonService.importData(list);
        return Result.success();
    }

    @Operation(summary = "导出亚马逊账号表", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:amazon:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "亚马逊账号表.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        List<SysAmazonImportVo> sysAmazonList = sysAmazonService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), SysAmazonImportVo.class).sheet("亚马逊账号表").doWrite(sysAmazonList);
    }
}

